﻿using ConsoleApp.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.MyLinq.Misc
{

    public static class Runner
    {
        // https://mp.weixin.qq.com/s/exAstBNtYkvT9oIVD3VQPw
        // https://blog.jeremylikness.com/blog/look-behind-the-iqueryable-curtain/

        public static void Run()
        {
            Demo03();
        }

        public static void Demo01()
        {
            var query = Thing.Things(500).AsQueryable()
                .Where(t => t.Name.Contains("a", StringComparison.InvariantCultureIgnoreCase) && t.Created > DateTimeOffset.Now.AddDays(-1))
                .Skip(2)
                .Take(50)
                .OrderBy(t => t.Created);

            new BasicExpressionConsoleWriter().Visit(query.Expression);

            Console.WriteLine("------");

            new ExpressionConsoleWriter().Visit(query.Expression);
        }

        public static void Demo02()
        {
            var query = Thing.Things(500).AsQueryable()
                .Where(t =>
                  t.Name.Contains("a", StringComparison.InvariantCultureIgnoreCase) &&
                  t.Created > DateTimeOffset.Now.AddDays(-1) &&
                  t.Name.Take(50) != null
                )
                .Skip(2)
                .Take(50)
                .OrderBy(t => t.Created);
            new ExpressionConsoleWriter().Parse(new ExpressionTakeRestrainer().ParseAndConstrainTake(query.Expression, 5));
        }

        public static void Demo03()
        {
            var query = Thing.Things(500).AsQueryable()
                .Where(t =>
                  t.Name.Contains("a", StringComparison.InvariantCultureIgnoreCase) &&
                  t.Created > DateTimeOffset.Now.AddDays(-1) &&
                  t.Name.Take(50) != null
                )
                .Skip(2)
                .Take(50)
                .OrderBy(t => t.Created);
            var transformedQuery = new TranslatingHost<Thing>(query, 5);
            new ExpressionConsoleWriter().Parse(transformedQuery.Expression);
            var list = transformedQuery.ToList();

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine($"Modified query results: {list.Count}");
        }
    }
}
